import json
import inspect
from django.http import HttpResponse

def jsonpost(request, scope):
    """
    """
    cmddc = json.loads(request.body)
    outdc = {}
    orderls = cmddc.pop('order', None)
    if orderls:
        for k in orderls:
            func = scope[k]
            kw=cmddc.pop(k)
            outdc[k]=_run_func(func, request,**kw)

    for k, kw in cmddc.items():
        func = scope[k]
        outdc[k]=_run_func(func, request,**kw)
    
    outdc['status']='success'
    return HttpResponse(json.dumps(outdc), content_type="application/json")


def _run_func(func,request,**kw):
    args=inspect.getargspec(func).args
    if 'request' in args:
        kw['request']=request
    if 'user' in args:
        if request.user.is_authenticated():
        # user=_get_user(request)
        # if user:
            kw['user']=request.user
        else:
            raise UserWarning,'function need user ,but canot get user from request'
            
    return func(**kw)